require 'pp'
require 'depac-common/softlayer'
require 'depac-common/qingcloud'
require 'depac-deployment/environment_configuration'
require 'depac-common/constants'
require 'securerandom'
require 'fileutils'
require 'yaml'

module Depac
module CBT_QC
  

def self.deleteEnvironment(configObject, flag)

	#roles =  configObject.getRoleArrayByType(type)
	roles = configObject.getRoleArray()
	
	if flag.length > 0
	  
	  _roles=flag
	else
    _roles=roles
	end
	
	if _roles.length > 0	
		#add the role that user dont want to delete by indicating command line flag value
		#roles = roles + flag
    _roles.each do |role|

			  hostIPArray = configObject.getHostnameIPMapByRoleAndType(role, nil)
       
			  hostIPArray.each do |hostIPMap|
				  hostIPMap.each do |machine|
					 hostName = machine['hostname']
					 ip = machine['IP']
					 vmid = machine['vmid']
					 if hostName != nil
						 
						 #deleteInstanceByIP(ip)
             deleteInstHash={
                                instances_N: nil,
                                zone: nil       
                            }                             
             deleteInstHash[:instances_N]=[vmid]
             
             zone= (configObject.getVMConfigByRole(role))[:zone] 
               
             if zone !=nil
                  deleteInstHash[:zone]= (configObject.getVMConfigByRole(role))[:zone] 
             end 
             Depac::Log.write("INFO", "Deleting Machine: hostname=#{hostName} ip=#{ip} vmid=#{vmid} zone=#{zone}")
             $qcmgr.deleteInstance(deleteInstHash)
					 end
				 end
			 end
		end
	end
	
end


def self.buildNodeInfoMapByRole(existingEnvConfigObject,currentRole)
   nodeInfoParamMap = Hash.new
  
   envConfig = existingEnvConfigObject.getEnvironmentConfiguration()

   roleInfoMap = Hash.new
    envConfig[:vms].each do |roleConfig|
      
       if(roleConfig[Depac::CloudDeploymentConstants::ROLE] == currentRole)
          roleInfoMap[currentRole] = roleConfig[Depac::CloudDeploymentConstants::NODE_INFO]
        end
   end
   nodeInfoParamMap[type] = roleInfoMap

  return nodeInfoParamMap
end

def self.buildNodeInfoMap(envConfigObject)
     nodeInfoMap=Hash.new
     envConfig = envConfigObject.getEnvironmentConfiguration()
     envConfig[:vms].each do |roleConfig|
       currentRole=roleConfig['role']
       nodeInfoMap[currentRole] = roleConfig[Depac::CloudDeploymentConstants::NODE_INFO]
     end
     return nodeInfoMap
end


def self.updateBuildLable(envConfigObject,buildLabel)
  envconfig = envConfigObject.getEnvironmentConfiguration()
  envconfig["build_label"]=buildLabel
end


end
end
